import CryptoJS from 'crypto-js';
import { find, map, each } from 'lodash';


const getShopcartData = () => {
    let encryptResult = localStorage.getItem('xinwei');
    let shopcartData = null;
    if (encryptResult) {
        encryptResult = CryptoJS.AES.decrypt(encryptResult.toString(), 'huange');
        encryptResult = encryptResult.toString(CryptoJS.enc.Utf8);
        shopcartData = JSON.parse(encryptResult);
    }
    return shopcartData;
};


const setShopcartData = (shopcartData) => {
    // 如果离线购物车的localStorage里没有数据时，就给一个空数组
    const shopcartList = getShopcartData() || [];
    const currentShopcartData = find(shopcartList, item => item.goodsId === shopcartData.goodsId);
    
    // 判断购物车中是否存在要添加的商品的数据，有就更新，没有就加
        
    
    if (currentShopcartData) {
        // 判断添加商品的购物车数量是否超出库存数量
        const resultQuantity = currentShopcartData.quantity + shopcartData.quantity;
        if (resultQuantity > shopcartData.stockQuantity) {
            return '库存不足，请重新操作！';
        }
        map(shopcartList, item => {
            if (item.goodsId === shopcartData.goodsId) {
                item.quantity += shopcartData.quantity;
            }
            return item;
        });
    } else {
        shopcartList.push(shopcartData);
    }
    const shopcartListStr = JSON.stringify(shopcartList);
    const encryptResult = CryptoJS.AES.encrypt(shopcartListStr, 'huange');
    localStorage.setItem('xinwei', encryptResult);
};

const removeShopcartData = () => {
    localStorage.removeItem('xinwei');
};

export default {
    getShopcartData,
    setShopcartData,
    removeShopcartData,
};